package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.BaseException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    /**
     * 微信登录
     *
     * @param userLoginDTO
     * @return
     */
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    //微信登录的get URL
    public static final String WEIXIN_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //1.调用微信接口（HttpClient），实现登录功能
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");

        String result = HttpClientUtil.doGet(WEIXIN_LOGIN_URL, paramMap);
        log.info("微信登录完成，结果：{}", result);
        //判空
        if (!StringUtils.hasLength(result)) {
            throw new BaseException(MessageConstant.LOGIN_FAILED);//登陆失败
        }

        //解析json
        JSONObject jsonObject = JSON.parseObject(result);

        String openid = jsonObject.getString("openid");
        //判空
        if (!StringUtils.hasLength(openid)) {
            throw new BaseException(MessageConstant.LOGIN_FAILED);//登陆失败
        }
        //2.如果用户是第一次访问小程序，则需要完成自动注册（insert）功能
        //先查在加
        User user = userMapper.selectByOpenid(openid);
        if (user == null) {//openid不在user表中，说明新用户
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        //3.返回数据
        return user;
    }
}
